package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.respository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.StringUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/7/11.
 */
@Service
public class TravelCommentServiceImpl implements ITravelCommentService{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ITravelCommentRepository dao;
    @Override
    public TravelComment save(TravelComment travelComment) {
        //游记标题
        //创建时间
        if (travelComment.getId()==null){
            travelComment.setCreateTime(new Date());
        }
        //关联的子评论
        if (travelComment.getRefComment()!=null && !StringUtil.notHasLength(travelComment.getRefComment().getId()+"")){
            travelComment.setRefComment(this.get(travelComment.getRefComment().getId()));
        }
        //点赞数
        //评论点赞的人
        dao.save(travelComment);
        return travelComment;
    }

    private TravelComment get(String id) {
        return dao.findById(id).get();
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        //设置参数
        Criteria criteria = null;
        if (qo.getTravelId()!=-1){
            criteria=Criteria.where("travelId").is(qo.getTravelId());
        }else {
            criteria=Criteria.where("travelId").ne(qo.getTravelId());
        }


       /* if (qo.getKeyword() != null){
            criteria.and("content").regex("^.*"+qo.getKeyword()+".*$");
        }*/
        query.addCriteria(criteria);//添加查询条件
        //查询总条数
        long total = mongoTemplate.count(query, TravelComment.class);
        if (total==0){
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);
        //排序
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        query.with(sort);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);


        PageImpl<TravelComment> pageImpl = new PageImpl<TravelComment>(list,pageable,total);
        return pageImpl;
    }
}
